import { getToken, setToken, removeToken } from "@/utils/auth.js"
import { login, logout, getInfo } from "@/api/login.js"
import { getNoInternallyConfig } from "@/api/system/config.js"
import { download } from "@/api/file.js";
import router from '@/router/index.js'
import modal from "@/plugins/modal.js"

/**
 * 用户相关信息存储
 */
const user = {
  state: {
    token: getToken(),
    userId: undefined,
    name: undefined,
    avatar: undefined,
    avatarUrl: undefined,
    roles: [],
    permissions: [],
    config: {}
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
      setToken(token)
    },
    SET_ID: (state, userId) => {
      state.userId = userId
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      if (avatar) {
        download(avatar).then(response => {
          state.avatarUrl = URL.createObjectURL(response.data);
        });
      } else {
        state.avatarUrl = require("@/assets/avatar/default.jpg");
      }
      state.avatar = avatar;
    },

    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    },
    SET_CONFIG: (state, config) => {
      state.config = config
    }
  },
  // actions是异步的，通过this.$store.dispatch 调用 返回Promise对象
  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password

      // 发起登录请求
      return new Promise((resolve, reject) => {
        login(username, password).then(res => {
          let data = res.data
          if (data && data.access_token) {
            commit('SET_TOKEN', data.access_token)
          }
          resolve(res);
        }).catch(error => {
          reject(error)
        })
      });
    },
    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo().then(res => {
          const data = res.data
          const user = data.user
          if (data.roles && data.roles.length > 0) { // 验证返回的roles是否是一个非空数组
            commit('SET_ROLES', data.roles)
            commit('SET_PERMISSIONS', data.permissions)
          } else {
            commit('SET_ROLES', ['ROLE_DEFAULT'])
          }
          commit('SET_ID', user.userId)
          commit('SET_NAME', user.userName)
          state.avatarUrl = null;
          commit('SET_AVATAR', user.avatar)
          resolve(data)
        })
      });
    },
    // 刷新token
    RefreshToken({ commit, state }) {

    },
    // 获取系统配置
    GetConfig({ commit, state }) {
      getNoInternallyConfig().then(res => {
        const _temp = {}
        Object.assign(_temp, ...res.data)
        commit("SET_CONFIG", _temp);
      })
    },
    // 退出系统
    Logout({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout().then(res => {
          commit("SET_TOKEN", null)
          commit("SET_AVATAR", "")
          // 删除token
          removeToken()
          // 删除权限
          commit("SET_ROLES", []);
          commit("SET_PERMISSIONS", []);
          // 跳转页面
          router.push("/login");
          modal.msgSuccess("成功退出登录!");
          resolve()
        })
      })
    }
  }
}

export default user